<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			title="批量-设定工艺"
			width="1200px"
			:show-content-loading="showContentLoading"
			:confirm-btn-loading="saveBtnLoading"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
				<div ref="box1">
					<el-tag class="margin-bottom-4" type="primary" effect="plain">
						<span class="el-icon-tickets"></span>
						<span>基本信息</span>
					</el-tag>
					<jk-card>
						<el-row class="flex-start-center-wrap">
							<el-col :span="24">
								<el-form-item class="margin-bottom-10" label="机台">
									<span class="read-only-2">{{ ruleForm.settingsList ? ruleForm.settingsList.map(x => x.machineName).join(',') : '' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="品种">
									<span class="read-only-2">{{ ruleForm.productName }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="批号">
									<span class="read-only-2">{{ ruleForm.batchCode }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="品种工艺单">
									<remote-search-technology-order-input
										placeholder="用户工艺编号"
										only-key="specSheetId"
										query-name="specSheetCode"
										:form-data="{
											specSheetId: ruleForm.specSheetId,
											specSheetCode: ruleForm.specSheetCode,
											productName: ruleForm.productName,
											batchCode: ruleForm.batchCode,
											machineModelName: ruleForm.machineModelName,
											spinTypeId: ruleForm.spinTypeId,
											code: ruleForm.batchOneList && ruleForm.batchOneList.length ? ruleForm.batchOneList[0] : '',
										}"
										@on-select="onSelectTechnologyOrderChange"
									></remote-search-technology-order-input>
								</el-form-item>
							</el-col>
							<!--<el-col :span="16">
                                <el-form-item class="margin-bottom-0" label="备注">
                                    <jk-input v-model="ruleForm.remark" type="textarea" :rows="1"></jk-input>
                                </el-form-item>
                            </el-col>-->
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" class="flex-between-center margin-bottom-4 margin-top-10">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-connection"></span>
						<span>工艺项目明细</span>
					</el-tag>
					<div class="flex-start-center" style="align-items: flex-end;font-size: 12px;">
						<jk-button size="mini" plain type="primary" icon="el-icon-plus" effect="plain" @click="onAddBtn">品种工艺单</jk-button>
					</div>
				</div>
				<jk-table ref="jkTable" border :data="ruleForm.specSheet.specSheetParamList || []" :height="dialogTableHeight - 20">
					<vxe-column title="序号" type="seq" align="center" :width="60"></vxe-column>
					<vxe-column title="项目名称" align="left" field="specParamName" :min-width="160"></vxe-column>
					<vxe-column title="数据类型" align="center" field="dataType" :min-width="160">
						<template slot-scope="scope">
							<span>{{ scope.row.dataType === 1 ? '数字型' : '字符型' }}</span>
						</template>
					</vxe-column>
					<vxe-column title="标准值" align="right" field="name" :min-width="160">
						<template slot-scope="scope">
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.val" size="mini" @change="onErrPerChange($event, scope)"></jk-number-input>
							<jk-input v-else v-model="scope.row.val" size="mini" placeholder=""></jk-input>
						</template>
					</vxe-column>
					<vxe-column title="误差(%)" align="right" field="name" :min-width="160">
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.plusOrMinus" :disabled="!scope.row.val" size="mini" class="width-100-percent" @change="onErrPerChange($event, scope)"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column title="上限" align="right" field="valMax" :min-width="160">
						<template slot-scope="scope">
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMin" size="mini"></jk-number-input>
							<jk-input v-else v-model="scope.row.valMin" size="mini" placeholder=""></jk-input>
						</template>
					</vxe-column>
					<vxe-column title="下限" align="right" field="valMin" :min-width="160">
						<template slot-scope="scope">
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMax" size="mini"></jk-number-input>
							<jk-input v-else v-model="scope.row.valMax" size="mini" placeholder=""></jk-input>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
		<add-technology-dialog
			:default-data="defaultData"
			:code-list="ruleForm.batchOneList || []"
			:dialog-state="addTechnologyDialogState"
			@on-visible-change="onVisibleChangeOfAddTechnology"
			@on-confirm="onConfirmBtnOfAddTechnology"
		></add-technology-dialog>
		<technology-detail-dialog
			:data-id="technologyOrderId"
			:dialog-state="technologyDetailDialogState"
			@on-visible-change="onVisibleChangeOfTechnologyDetailDialog"
		></technology-detail-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input/index';
    import { spinSpecSheetGet } from '../../../api/technology/order';
    import addTechnologyDialog from '../../technology/task/add-technology-dialog';
    import technologyDetailDialog from '../../technology/task/technology-detail-dialog';
    import {
        productionTechnologySettingsBatchSetSpec,
        productionTechnologySettingsUpdate
    } from '../../../api/technology/technologySet';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { mathJsAdd, mathJsMul, mathJsSub } from '../../../utils/jk/jk-cals';
    import remoteSearchTechnologyOrderInput from '../order/components/remote-search-technology-order-input';
    export default {
        mixins: [calHeight],
        components: {
            remoteSearchTechnologyOrderInput,
            technologyDetailDialog,
            addTechnologyDialog,
            remoteSearchProductInput
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            checkData: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                defaultData: {},
                spinTypeList: [],
                tableData: [],
                saveBtnLoading: false,
                showDialog: false,
                showContentLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    specSheet: {}
                },
                rules: {
                    specSheetId: [{ required: true, trigger: 'change' }]
                },
                technologyOrderId: null,
                addTechnologyDialogState: false,
                technologyDetailDialogState: false,
                searchParams: {
                    productName: '',
                    batchCode: '',
                    processId: '',
                    spinTypeId: null,
                    machineModelName: '',
                    code: ''
                },
                processList: [],
                tableLoading: false
            };
        },
        methods: {
            onSelectTechnologyOrderChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'specSheetId', e.id);
                    this.getTechnologyDetailRequest();
                } else {
                    this.$set(this.ruleForm, 'specSheet', {});
                }
            },
            onErrPerChange(e, scope) {
                if (e && this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].dataType === 1 && this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].plusOrMinus) {
                    let val = mathJsMul(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].val, (this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].plusOrMinus / 100));
                    val = Number(val.toFixed(2));
                    this.$set(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex], 'valMin', mathJsSub(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].val, val));
                    this.$set(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex], 'valMax', mathJsAdd(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].val, val));
                } else {
                    if (this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].dataType === 1) {
                        this.$set(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex], 'valMin', this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].val);
                        this.$set(this.ruleForm.specSheet.specSheetParamList[scope.rowIndex], 'valMax', this.ruleForm.specSheet.specSheetParamList[scope.rowIndex].val);
                    }
                }
            },
            getTechnologyDetailRequest() {
                this.$set(this.ruleForm, 'specSheet', {});
                if (!this.ruleForm.specSheetId) return;
                return spinSpecSheetGet({
                    id: this.ruleForm.specSheetId
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.specSheetParamList = this.transformItemData(resData.specSheetParamList);

                        this.$set(this.ruleForm, 'specSheetCode', resData.code);
                        this.$set(this.ruleForm, 'specSheet', resData || {});
                    }
                });
            },
            onVisibleChangeOfTechnologyDetailDialog(e) {
                this.technologyDetailDialogState = e;
            },
            onAddBtn() {
                this.defaultData = {
                    productId: this.ruleForm.productId,
                    productCode: this.ruleForm.productCode,
                    productName: this.ruleForm.productName,
                    productModels: this.ruleForm.productModels,
                    batchId: this.ruleForm.batchId,
                    batchCode: this.ruleForm.batchCode
                };
                this.addTechnologyDialogState = true;
            },
            onConfirmBtnOfAddTechnology(id) {
                this.$set(this.ruleForm, 'specSheetId', id);
                this.getTechnologyDetailRequest();
                this.addTechnologyDialogState = false;
            },
            onVisibleChangeOfAddTechnology(e) {
                this.addTechnologyDialogState = e;
            },
            onDetailBtn(scope) {
                this.technologyOrderId = scope.row.id;
                this.technologyDetailDialogState = true;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid && this.ruleForm.specSheetId) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                productionTechnologySettingsBatchSetSpec(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            transformItemData(list) {
                let arr = [];
                arr = list.map(x => {
                    x.val = x.dataType === 1 ? Number(x.val) : x.val;
                    x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
                    x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
                    return x;
                });
                return arr;
            },
            async getDependentData() {
                this.showContentLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                await this.getSpinTypeListRequest();
                this.showContentLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    const cpData = this.checkData ? JSON.parse(JSON.stringify(this.checkData)) : [];
                    const productInfo = cpData && cpData.length ? cpData[0] : {};
                    this.ruleForm = {
                        productId: productInfo.productId,
                        productCode: productInfo.productCode,
                        productName: productInfo.productName,
                        batchCode: productInfo.batchCode,
                        settingsList: cpData.map(x => {
                            return {
                                id: x.id,
                                machineId: x.machineId,
                                machineCode: x.machineCode,
                                machineName: x.machineName
                            };
                        }),
                        specSheet: {}
                    };
                    this.getDependentData();
                }
            }
        }
    };
</script>
